package posti.test.swf.service;

import posti.test.swf.dao.GenericDAO;
import posti.test.swf.dao.Reference;
import posti.test.swf.web.action.Mapping;
import posti.test.swf.web.action.MappingsFactory;

/**
 * Business Delegate. vive en la capa del appserver
 * Expone el servicio y es tesponsable de hacer transformaciones de objetos de dominio a dto.
 * Definitivamente candidato a ser reemplazado por aspect
 * @author Posti
 */
public class CRUDServiceDelegate {
	private GenericDAO dao;
	private CRUDService crudService;

	protected CRUDServiceDelegate() {}
	public CRUDServiceDelegate(CRUDService crudService) {
		this.crudService = crudService;
	}

	public Object retrieve(Mapping mapping, Reference dto) {
		//TODO cambiar esto, no debe recibir dto sino directamente un reference
//		Mapping<Object, Object> mapping = mappingFactory.getMapping(contextId);
		Object domainObject = crudService.retrieve(dto);

		return mapping.toDTO(domainObject);
	}
	public Object save(Mapping mapping, Object dto) {
//		Mapping<Object, Object> mapping = mappingFactory.getMapping(contextId);
		Object domainObject = (mapping.isNew(dto))?
								mapping.newInstance(dto) : 
								dao.load(mapping.reference(dto));

		mapping.synchronize(domainObject, dto);

		Object returnValue = crudService.save(domainObject);

		return mapping.toDTO(returnValue);
	}

	public void delete(Mapping mapping, Object dto) {
//		Mapping<Object, Object> mapping = mappingFactory.getMapping(contextId);
		Object domainObject = dao.load(mapping.reference(dto));

		crudService.delete(domainObject);
	}

	/** @deprecated **/
	public void setBeanMapper(MappingsFactory mappingFactory) {
	}
	public void setCrudService(CRUDService crudService) {
		this.crudService = crudService;
	}
	
	public void setGenericDAO(GenericDAO dao) {
		this.dao = dao;
	}
}
